package wickethub.web.app;

import javax.persistence.EntityNotFoundException;

import org.apache.wicket.model.IModel;

import wickethub.domain.Resource;
import wickethub.repository.Repository;

public class EntityDetachableModel<T extends Resource> implements IModel<T> {
	
	private Class<?> clazz;
	private Long id;
	private Repository<Resource> repo;
	private T entity;

	public EntityDetachableModel(T entity, Repository<Resource> repo) {
		clazz = entity.getClass();
		id = entity.getId();
		this.entity = entity;
		this.repo = repo;
	}
	
	public EntityDetachableModel(Class<? extends T> clazz, Long id, Repository<Resource> repo) {
		this.clazz = clazz;
		this.id = id;
		this.repo = repo;
	}
	
	@SuppressWarnings("unchecked")
	protected T load(Class<?> clazz, Long id) {
		return (T) repo.getById(id);
	}
	
    public T getObject() {
        if (entity == null) {
            if (id != null) {
                entity = load(clazz, id);
                if (entity == null) {
                    throw new EntityNotFoundException();
                }
            }
        }
        return entity;
    }
 
    public void detach() {
        if (entity != null) {
            if (entity.getId() != null) {
                id = entity.getId();
                entity = null;
            }
        }
    }
    
    public void setObject(T object) {
        throw new UnsupportedOperationException(getClass() +
                " does not support #setObject(T entity)");
    }
	
}